import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/hotel'
  },
  {
    path: '/hotel',
    name: 'Hotel',
    component: () => import('@/views/Hotel.vue'),
    children: [
      {
        path: '/',
        name: 'HomeHotelContainer',
        component: () => import('@/views/HomeHotelContainer.vue')
      },
      {
        path: 'detail/:id',
        name: 'HotelDetail',
        component: () => import('@/views/HotelDetail.vue'),
      }
    ]
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/mypage',
    name: 'MyPage',
    component: () => import('@/views/MyPage.vue'),
    children: [
      {
        path: 'myhome',
        name: 'MyHome',
        component: () => import('@/views/MyHome.vue')
      },
      {
        path: 'myorder',
        name: 'MyOrder',
        component: () => import('@/views/MyOrder.vue'),
      }
    ]
  },
  {
    path: '/pay',
    name: 'Pay',
    component: () => import('@/views/Pay.vue'),
  }
]

const router = new VueRouter({
  // mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

router.beforeEach((to, from, next) => {
  next()
  let phone = localStorage.getItem('user_phone')
  if (phone) {
    // 已登录
    if (to.path == "/login" || to.path == "/register") {
      next("/")
    } else {
      next()
    }
  } else {
    // 未登录
    let toPath = to.path;
    if (toPath.indexOf("/mypage") != -1 || toPath.indexOf("/hotel/detail") != -1) {
      next("/login?redirect=" + toPath)
    } else {
      next()
    }
  }
})

export default router
